package com.maezia.tdr.common.redis;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;

@Slf4j
public class FastJsonSerializer<T> implements RedisSerializer<T> {
    static final byte[] EMPTY_ARRAY = new byte[0];

    private Class<T> clazz;

    public FastJsonSerializer(Class<T> clazz) {
        this.clazz = clazz;
    }

    @Override
    public byte[] serialize(T t) throws SerializationException {
        if(null != t) {
            return JSON.toJSONBytes(t,
                    SerializerFeature.WriteNullBooleanAsFalse,
                    SerializerFeature.WriteNullNumberAsZero,
                    SerializerFeature.WriteNullStringAsEmpty);
        }
        return EMPTY_ARRAY;
    }

    @Override
    public T deserialize(byte[] bytes) throws SerializationException {
        if (bytes == null || bytes.length == 0) {
            return null;
        }
        try {
            return JSON.parseObject(bytes, clazz);
        } catch (Exception e) {
            log.error("fastJsonSerializer-deserialize", e);
        }
        return null;
    }

    public void setClazz(Class<T> clazz) {
        this.clazz = clazz;
    }
}

